﻿using Abp.Auditing;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Basefr.Logging.Auditings
{
    internal static class AuditingLoggerExtensions
    {
        /// <summary>
        /// 使用NLog记录Abp的AuditLog
        /// </summary>
        internal static void LogAudit(this Castle.Core.Logging.ILogger logger, AuditInfo auditLog, LogLevel level)
        {
            var logInfo = new LogEventInfo();

            auditLog.GetType().GetProperties().ToList().ForEach(p => logInfo.Properties[p.Name] = p.GetValue(auditLog));

            if (auditLog.Exception != null)
            {
                var messages = new List<string>();

                GetMessage(auditLog.Exception);

                void GetMessage(Exception exception)
                {
                    messages.Add(exception.Message);
                    if (exception.InnerException != null)
                    {
                        GetMessage(exception.InnerException);
                    }
                }

                logInfo.Properties["IsFailed"] = true;
                logInfo.Properties["ExceptionMessage"] = string.Join("-->", messages);
                logInfo.Properties["ExceptionStackTrace"] = auditLog.Exception.StackTrace;
            }
            else
            {
                logInfo.Properties["IsFailed"] = false;
                logInfo.Properties["ExceptionMessage"] = null;
                logInfo.Properties["ExceptionStackTrace"] = null;
            }

            //(logger as NLogLogger)?.Instance.Log(level, logInfo);
        }
    }
}
